import { NameSpace } from 'utils/index';
import exceed from 'utils/apimap';

const ns = NameSpace('project-pipeline');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RECEIVE_DATA = ns('RECEIVE_DATA');
export const SET_TAB_KEY = ns('SET_TAB_KEY');
export const SET_SEARCH = ns('SET_SEARCH');
export const SET_ADVANCEDSEARCHDATA = ns('SET_ADVANCEDSEARCHDATA');
export const SET_RESET_LIST = ns('SET_RESET_LIST');
export const SET_LOADING = ns('SET_LOADING');
export const RESET_DATA = ns('RESET_DATA');

const { pathResource } = window.FORCE;

export function resetData() {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
    });
  };
}

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function getPipelines(page, isDidMount, extra = {}) {
  return (dispatch, getState) => {
    const states = getState().project.projectPipeline;
    const { search, tabKey, advancedSearchData, pageSize = 10 } = states;
    if (!extra.noLoading) {
      dispatch({
        type: SET_LOADING,
      });
    }
    if (!extra.branch_name) {
      extra.branch_name = window.FORCE.pathResource.defaultBranch;
    }
    exceed
      .fetch({
        api: `project.pipelines${tabKey === 'branch' ? '.branch' : ''}`,
        params: {
          projectId: pathResource.id,
        },
        data: { ...advancedSearchData, search, per_page: pageSize, page, ...extra },
      })
      .then((res) => {
        const list = res.slice(1);
        const total = res[0].amount;
        dispatch({
          type: RECEIVE_DATA,
          data: {
            list,
            currentPage: page,
            total,
            isDidMount,
          },
        });
      })
      .fail(console.log);
  };
}

export function setTabKey(data, noReset) {
  return (dispatch) => {
    dispatch({
      type: SET_TAB_KEY,
      data,
    });

    if (!noReset) dispatch(setResetList());
  };
}

export function setSearch(data) {
  return (dispatch) => {
    dispatch({
      type: SET_SEARCH,
      data,
    });

    dispatch(setResetList());
  };
}

export function setResetList() {
  return (dispatch) => {
    dispatch({
      type: SET_RESET_LIST,
    });

    dispatch(getPipelines(1));
  };
}

export function setAdvancedSearch(data) {
  return (dispatch) => {
    dispatch({
      type: SET_ADVANCEDSEARCHDATA,
      data,
    });

    dispatch(getPipelines(1));
  };
}
